package com.aydqyy.springbootstart.controller;

import com.aydqyy.springbootstart.dto.UserDTO;
import com.aydqyy.springbootstart.common.exception.Result;
import com.aydqyy.springbootstart.entity.User;
import com.aydqyy.springbootstart.service.UserService;
import com.aydqyy.springbootstart.utils.JwtUtil;
import com.aydqyy.springbootstart.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/register")
    public Result register(@RequestParam("name") @Pattern(regexp = "^\\S{5,16}$") String name, @RequestParam("password") @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = this.userService.getByName(name);
        if (user != null) {
            return Result.error("用户已经存在");
        }
        user = new User();
        user.setName(name);
        user.setPassword(password);

        boolean res = this.userService.saveOrUpdate(user);
        if (res)
            return Result.success();
        else
            return Result.error("注册失败");
    }

    @RequestMapping("/list")
    public  Result<List<User>> userList() {
        List<User> userList = this.userService.list();
        return Result.success(userList);
    }

    @RequestMapping("/login")
    public Result login(@RequestParam("name") String name, @RequestParam("password") String password) {
        User user = this.userService.getByName(name);
        if (user == null)
            return Result.error("用户名不存在！");
        else {
            if (!password.equals(user.getPassword()))
                return Result.error("登录失败");
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("name", user.getName());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);

        }
    }

    @RequestMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token) {

        String userName = this.getUserName2();
        User user = this.userService.getByName(userName);
        return Result.success(user);
    }

    //通过解析header中的Authorization获得用户信息
    private String getUserName(String token) {
        Map<String, Object> claims = JwtUtil.parseToken(token);
        return (String) claims.get("name");
    }

    //通过线程本地变量获得登录用户的信息
    private String getUserName2() {
        Map<String, Object> claims = (Map<String, Object>) ThreadLocalUtil.getValue();
        return (String) claims.get("name");
    }

    @PatchMapping("update")
    public Result update(@RequestBody @Validated(UserDTO.Update.class) UserDTO userUpdateDTO) {
        User user = this.userService.getById(userUpdateDTO.getId());
        if (user == null)
            return Result.error("用户不存在！");
        user.setName(userUpdateDTO.getName());
        user.setPassword(userUpdateDTO.getPassword());
        if (!this.userService.saveOrUpdate(user))
            return Result.error("更新失败！");
        return Result.success(user);
    }

    @PatchMapping("updatePassword")
    public Result updatePassword(@RequestBody @Validated(UserDTO.UpdatePassword.class) UserDTO userUpdateDTO) {
        User user = this.userService.getById(userUpdateDTO.getId());
        if (user == null)
            return Result.error("用户不存在！");
        if (!user.getPassword().equals(userUpdateDTO.getOldPassword()))
            return Result.error("原始密码不正确");
/*       if(!userUpdateDTO.getPassword().equals(userUpdateDTO.getRePassword()))
           return Result.error("两次密码不一致");*/
        user.setPassword(userUpdateDTO.getPassword());
        if (!this.userService.saveOrUpdate(user))
            return Result.error("更新失败！");
        return Result.success(user);
    }

}
